package net.dfx.iot_download_tool.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;

import javax.net.ssl.HttpsURLConnection;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson2.JSONObject;

import net.dfx.iot_download_tool.enu.ReqUrlEnum;
import net.dfx.iot_download_tool.vo.ApikeyVO;

public class ApiKeyUtil {

	static Logger logger = LogManager.getLogger(ApiKeyUtil.class);
	TrustAllUtil trustAllUtil = new TrustAllUtil();
	
	/**
	 * 请求IOT的key接口获取API KEY
	 * @return {@link ApikeyVO}配置对象
	 */
	public ApikeyVO getApiKey() {
		ApikeyVO configVO = new ApikeyVO();
		// 获取API KEY
		String akurl = ReqUrlEnum.AKURL.getUrlStr();
		boolean testUrlRsult = testConnectivity(akurl);
		if (testUrlRsult) {
			logger.info("与服务端网络连接正常");
			URL akurls = null;
			try {
				akurls = new URL(akurl);
			} catch (MalformedURLException e) {
				logger.error(e);
			}
			try {
				HttpsURLConnection akconn = (HttpsURLConnection) akurls.openConnection();
				trustAllUtil.trustAllCertificates(akconn);
				akconn.setRequestMethod("GET");
				akconn.setConnectTimeout(1000 * 60 * 20);// 20分钟
				akconn.setReadTimeout(1000 * 60 * 20);// 20分钟
				int akrespCode = akconn.getResponseCode();
				logger.info("请求API Key响应状态码：" + akrespCode);
				if (akrespCode == HttpURLConnection.HTTP_OK) {
					StringBuilder responseBody = new StringBuilder();
					try (BufferedReader reader = new BufferedReader(
							new InputStreamReader(akconn.getInputStream(), StandardCharsets.UTF_8))) {
						String line;
						while ((line = reader.readLine()) != null) {
							responseBody.append(line);
						}
					}
					JSONObject rootObj = JSONObject.parseObject(responseBody.toString());
					String ab = rootObj.getString("data");
					if (StringUtils.isNotBlank(ab)) {
						configVO.setApikey(ab);
					}
				}
			} catch (Exception e) {
				logger.error(e);
			}
			logger.info("download iot data success...");
			 
		} else {
			logger.error("无法访问服务器，请检查VPN网络连接及VPN访问权限！");
		}
		return configVO;
	}

	/**
	 * 测试网络连通性
	 *
	 * @param urlString 待测试网址
	 * @return boolean 测试结果，true-测试通过
	 */
	public boolean testConnectivity(String urlString) {
		try {
			logger.info("检测与IoT服务网络连接……");
			URL url = new URL(urlString);
			HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
			trustAllUtil.trustAllCertificates(connection);
			connection.setRequestMethod("GET");
			connection.setConnectTimeout(5000); // 设置连接超时时间（毫秒）
			connection.setReadTimeout(5000); // 设置读取超时时间（毫秒）
			int responseCode = connection.getResponseCode();
			return (200 <= responseCode && responseCode <= 299); // 检查响应码是否在2xx范围内
		} catch (Exception e) {
			logger.error(e);
			return false;
		}
	}
}
